<?php

namespace App\Http\Controllers\Frontend\V10\Users;

use App\Events\AuthStepEvent;
use App\Events\UploadIdCardEvent;
use App\Exceptions\GeneralException;
use App\Facades\SamLogFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\V10\Users\CretRequest;
use App\Http\Requests\Frontend\V10\Users\UserOcrGetInfoRequest;
use App\Http\Requests\Frontend\V10\Users\UserOcrStoreRequest;
use App\Library\Guzzle\OcrIssueCode;
use App\Library\Source\Rong360\R360CheckInfo;
use App\Models\User;
use App\Models\UserAuthStepEventLog;
use App\Models\UserCertOcr;
use App\Models\UserLoanRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserOcrController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    /**
     * Description:进入申请流程认证身份证
     * Author: Sam
     * DateTime: 2019/1/4 17:54
     * @param UserOcrStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function store(UserOcrStoreRequest $request)
    {
        /**
         * @var $user User
         */
        $user = Auth::user();
        $params = $this->extractInputFromRules($request,$request->rules());
        $params['user_id'] = $user->id;
//        $params['issue_gov_code'] = OcrIssueCode::getCode($params['issuing_authority']);
        $params['issue_gov_code'] = "0";
        $valid_date = explode('-',$params['valid_date']);
        foreach ($valid_date as $k =>$v){
            if($v!=='长期'){
                $valid_date[$k] = str_replace('.','-',$v);
            }
        }
        $exist = UserCertOcr::where('user_id',$user->id)
            ->where('is_valid',1)
            ->first();
        if($exist){
            return failed('已存在数据');
        }
        $params['valid_date_begin'] = date('Y-m-d',strtotime($valid_date[0]));
        $params['valid_date_end'] =$valid_date[1]=='长期'?'长期':date('Y-m-d',strtotime($valid_date[1]));
        $params['hand_cert'] = '';
        $loan = UserLoanRequest::where(['current'=>UserLoanRequest::CURRENT_NOW,'user_id'=>$user->id])->orderByDesc('id')->firstOrFail();
        DB::beginTransaction();
        try{
            $ocr = UserCertOcr::create($params);
            $loan->cert_ocr_id = $ocr->id;
            $loan->status = UserLoanRequest::STATUS_UN_APPLY;
            /**
             * @var $loan UserLoanRequest
             */
            $loan->save();
            $log = [
                'uid'=>$user->id,
                'step_id'=>$ocr->id,
                'type'=>UserAuthStepEventLog::STEP_OCR,
                'loan_request_id'=>$loan->id,
            ];
            event(new AuthStepEvent($log));
            DB::commit();
        }catch(\Exception $exception){
            SamLogFacade::debug("用户【{$user->id}】身份证信息录入失败：".$exception->getMessage());
            DB::rollBack();
            throw new GeneralException('服务器错误',500);
        }
        /**
         * 添加融360撞库数据
         */
//        R360CheckInfo::append($user);
        return success([]);
    }

    /**
     * Description:获取身份证信息
     * Author: Sam
     * DateTime: 2019/1/6 15:37
     * @param UserOcrGetInfoRequest $request
     * @return mixed
     */
    public function getInfo(UserOcrGetInfoRequest $request)
    {
        /**
         * @var $user User
         */
        $user =  $request->user();
        $info = $user->validCert()->first();
        return success($info);
    }

    /**
     * Description:单纯认证身份证
     * Author: Sam
     * DateTime: 2019-01-24 11:04
     * @param CretRequest $request
     * @return mixed
     */
    public function cert(CretRequest $request)
    {
        $user = Auth::user();
        $params = $this->extractInputFromRules($request,$request->rules());
        $params['user_id'] = $user->id;
        $params['issue_gov_code'] = OcrIssueCode::getCode($params['issuing_authority']);
        $valid_date = explode('-',$params['valid_date']);
        foreach ($valid_date as $k =>$v){
            if($v!=='长期'){
                $valid_date[$k] = str_replace('.','-',$v);
            }
        }
        $exist = UserCertOcr::where('user_id',$user->id)
            ->where('is_valid',1)
            ->first();
        if($exist){
            return failed('已存在数据');
        }
        $params['valid_date_begin'] = date('Y-m-d',strtotime($valid_date[0]));
        $params['valid_date_end'] =$valid_date[1]=='长期'?'长期':date('Y-m-d',strtotime($valid_date[1]));
        $params['hand_cert'] = '';
        $ocr = UserCertOcr::create($params);
        return success([]);
    }
}
